<?php


namespace shisou\tpinit\lib;

use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * 导入excel
 *
 * @param string $pathExcel 文件
 * @param array  $keyName   表单选=>数组key名称
 *
 * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
 */
class ImportExcel
{
    private $keyName;
    private $pathExcel;

    public function __construct($pathExcel, $keyName)
    {
        $this->keyName   = $keyName;
        $this->pathExcel = $pathExcel;
    }

    public function getData()
    {
        $excel       = public_path() . $this->pathExcel;

        $spreadsheet = IOFactory::load($excel);

        $sheet       = $spreadsheet->getActiveSheet();
        $highestRi   = $sheet->getHighestDataRow();

        // tables
        $tables  = [];

        $keyName = $this->keyName;

        for ($ri = 2; $ri <= $highestRi; $ri++) {
            foreach ($keyName as $k => $v) {
                if (count($keyName) > 1) {
                    $tables[$ri - 2][$v]   = trim($sheet->getCell($k . $ri)
                        ->getValue() ?: '');
                } else {
                    $tables[$ri - 2]   = trim($sheet->getCell($k . $ri)
                        ->getValue() ?: '');
                }
            }
        }

        return $tables;
    }
}
